<script lang="ts" setup>
import type { DatePickerBaseEvent } from 'nutui-uniapp'
import dayjs from 'dayjs'

const props = defineProps({
  title: {
    type: String,
    default: '日期'
  },
  min: {
    type: Date,
    default: dayjs('1949-01-01').toDate()
  },
  max: {
    type: Date,
    default: dayjs('2099-12-31').toDate()
  },
  inputAlign: {
    type: String,
    default: 'left',
  },
})

const model = defineModel({ type: String })

const now = dayjs()

const currentDate = ref<Date>(now.toDate())
const showPicker = ref(false)

function onConfirm({ date }: DatePickerBaseEvent) {
  model.value = dayjs(date).format('YYYY-MM-DD')
  showPicker.value = false
}

watch(() => model.value, (value) => {
  if (value){
    currentDate.value = dayjs(value).toDate()
  } else {
    currentDate.value = now.toDate()
  }
})

</script>

<template>
  <nut-input v-model="model" class="nut-input-text" :placeholder="`请选择${props.title}`" type="text" readonly
    @click="showPicker = true" :input-align="props.inputAlign" placeholder-style="color:#ccc;" />
  <nut-popup v-model:visible="showPicker" position="bottom" safe-area-inset-bottom>
    <nut-date-picker v-model="currentDate" :min-date="props.min" :max-date="props.max" :title="props.title"
      three-dimensional is-show-chinese @cancel="showPicker = false" @confirm="onConfirm">
    </nut-date-picker>
  </nut-popup>
</template>
